import type { RouteRecordRaw } from 'vue-router'
// 基于菜单的动态路由
function loadLocalRouter() {
  const localRouter: RouteRecordRaw[] = []
  const files: Record<string, any> = import.meta.glob('../router/main/**/*.ts', {
    eager: true
  })
  for (const key in files) {
    const module = files[key]
    localRouter.push(module.default)
  }
  return localRouter
}

export let firstMenu: any = null
export function mapMenusToRoutes(userMenus: any[]) {
  const localRouter = loadLocalRouter()

  const routes: RouteRecordRaw[] = []
  for (const menu of userMenus) {
    console.log(menu.single)

    for (const submenu of menu.children) {
      const route = localRouter.find((item) => item.path === submenu.url)
      if (route) {
        // 一级菜单加上重定向
        if (!routes.find((item) => item.path === menu.url)) {
          routes.push({ path: menu.url, redirect: route.path })
        }
        // 2.二级菜单路由
        routes.push(route)
      }
      if (!firstMenu && route) firstMenu = submenu
    }
  }
  return routes
}

// 根据路由匹配选中菜单
export function mapPathToMenu(path: string, userMenus: any[]) {
  for (const menu of userMenus) {
    for (const submenu of menu.children) {
      if (submenu.url === path) {
        return submenu
      }
    }
  }
}

// 面包屑
interface IBreadcrumbs {
  name: string
  path: string
}
export function mapPathToBteadcrumbs(path: string, userMenus: any[]) {
  // 1.面包屑
  const breadcrumbs: IBreadcrumbs[] = []
  // 2.获取面包屑的层级
  for (const menu of userMenus) {
    for (const submenu of menu.children) {
      if (submenu.url === path) {
        // 1.顶层菜单
        breadcrumbs.push({ name: menu.name, path: menu.url })
        // 2.匹配菜单
        breadcrumbs.push({ name: submenu.name, path: submenu.url })
      }
    }
  }
  return breadcrumbs
}
